<script setup lang="ts">
import { ref, unref } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { ElTree, ElButton, ElLoading, ElMessageBox } from 'element-plus'
import { ucRoleEditAdminApi, ucRoleDelAdminApi } from '@/api/uc/role'
import { ucOrgRoleAddAdminApi, ucOrgRoleListAdminApi } from '@/api/uc/orgRole'
import { ucRoleAppSetApi } from '@/api/uc/roleApp'
import { ucRoleMenuSetApi } from '@/api/uc/roleMenu'
import { ucRoleFaSetApi } from '@/api/uc/roleFa'
import { ucRoleDaSetApi } from '@/api/uc/roleDa'
import { useI18n } from '@/hooks/web/useI18n'
import { Dialog } from '@/components/Dialog'
import Edit from './components/Edit.vue'
import AppSet from './components/AppSet.vue'
import MenuSet from './components/MenuSet.vue'
import FunctionSet from './components/FunctionSet.vue'
import DataSet from './components/DataSet.vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const { t } = useI18n()
// const loading = ref(false)
const loading = ref({
  tree: false,
  save: false
})
const iconSize = 16
const iconColor = '#999'

const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')
const formData = ref<any>({})

const roleData = ref<any>([])
const defaultProps = {
  children: 'children',
  label: 'role_name'
}
const AppSetRef = ref<ComponentRef<typeof AppSet>>()
const MenuSetRef = ref<ComponentRef<typeof MenuSet>>()
const FaSetRef = ref<ComponentRef<typeof FunctionSet>>()
const DataSetRef = ref<ComponentRef<typeof DataSet>>()

const deleteApi = async (id) => {
  const res = await ucRoleDelAdminApi({ role_id: id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    // roleData.value = res.data
    getList()
  }
}

const action = (type: string, data?: any) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = t('编辑角色')
      formData.value = data
      if (formData.value.disp_order != null && typeof formData.value.disp_order === 'string') {
        formData.value.disp_order = Number(formData.value.disp_order)
      }
      dialogVisible.value = true
      break
    case 'addChildren':
      dialogTitle.value = t('新增下级角色')
      formData.value = {
        parent_id: data.role_id,
        is_sys: 0,
        disp_order: 0
      }
      dialogVisible.value = true
      break
    case 'add':
      if (roleData.value.length > 0) {
        dialogTitle.value = t('新增角色')
        formData.value = {
          parent_id: roleData.value[0].role_id,
          is_sys: '0',
          disp_order: 0
        }
        dialogVisible.value = true
      } else {
        alert('没有分配系统角色')
      }

      break
    case 'app': // 应用权限
      dialogTitle.value = '菜单权限'
      formData.value = data
      dialogVisible.value = true
      break
    case 'menu': // 菜单权限
      dialogTitle.value = '菜单权限'
      formData.value = data
      dialogVisible.value = true
      break
    case 'function': // 功能权限
      dialogTitle.value = '功能权限'
      formData.value = data
      dialogVisible.value = true
      break
    case 'data': // 数据权限
      dialogTitle.value = '数据权限'
      formData.value = data
      dialogVisible.value = true
      break
    case 'delete':
      ElMessageBox.confirm('确定要删除这个角色？', '删除角色', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteApi(data.role_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const getList = async (data = {}) => {
  // const loadingInstance = ElLoading.service(options)
  const loadingMain = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await ucOrgRoleListAdminApi({ ...data, org_id: route.query.org_id })
    .catch(() => {})
    .finally(() => {
      setTimeout(() => {
        loadingMain.close()
      }, 500)
    })
  if (res) {
    roleData.value = res.data
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
const save = async (type: string) => {
  let edit
  switch (type) {
    case 'edit':
      edit = unref(editRef)
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          // 点击后先让按钮loading
          loading.value.save = true
          const newData: any = await edit?.getFormData()
          if (newData.value != null) {
            newData.role_id = newData.value
          }
          if (newData.label != null) {
            newData.role_name = newData.label
          }
          const data = { ...edit.oldFormData, ...newData, org_id: route.query.org_id }
          const res = await ucRoleEditAdminApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value.save = false
            })
          if (res) {
            dialogVisible.value = false
            getList()
          }
        }
      })
      break
    case 'addChildren':
    case 'add':
      edit = unref(editRef)
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          // 点击后先让按钮loading
          loading.value.save = true
          const newData: any = await edit?.getFormData()
          const data = { ...edit.oldFormData, ...newData, org_id: route.query.org_id }
          const addRes = await ucOrgRoleAddAdminApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value.save = false
            })
          if (addRes) {
            dialogVisible.value = false
            getList()
          }
        }
      })
      break
    case 'app':
      let appSet = unref(AppSetRef)
      let ids: any = await appSet?.getCheckedKeys()
      let data: any = { role_id: formData.value.role_id, set: [] }
      ids.forEach((item) => {
        data.set.push({ app_id: item, authority: 1 })
      })
      loading.value.save = true
      const res = await ucRoleAppSetApi(data)
        .catch(() => {})
        .finally(() => {
          loading.value.save = false
        })
      if (res) {
        dialogVisible.value = false
      }
      break
    case 'menu':
      let menuSet = unref(MenuSetRef)
      let menuForm: any = await menuSet?.getForm()
      let menuData: any = { app_id: menuForm.app_id, role_id: formData.value.role_id, set: [] }
      menuForm.ids.forEach((item) => {
        menuData.set.push({ menu_id: item, authority: 1 })
      })
      loading.value.save = true
      const menuRes = await ucRoleMenuSetApi(menuData)
        .catch(() => {})
        .finally(() => {
          loading.value.save = false
        })
      if (menuRes) {
        dialogVisible.value = false
        // getList()
      }
      break
    case 'function':
      let faSet = unref(FaSetRef)
      let faForm: any = await faSet?.getForm()
      let faData: any = { app_id: faForm.app_id, role_id: formData.value.role_id, set: [] }
      faForm.ids.forEach((item) => {
        faData.set.push({ fa_id: item, authority: 1 })
      })
      loading.value.save = true
      const faRes = await ucRoleFaSetApi(faData)
        .catch(() => {})
        .finally(() => {
          loading.value.save = false
        })
      if (faRes) {
        dialogVisible.value = false
      }
      break
    case 'data':
      let daSet = unref(DataSetRef)
      let daForm: any = await daSet?.getForm()
      let daData: any = { app_id: daForm.app_id, role_id: formData.value.role_id, set: [] }
      for (let key in daForm.ids) {
        daData.set.push({ da_id: key, authority: daForm.ids[key] })
      }
      loading.value.save = true
      const daRes = await ucRoleDaSetApi(daData)
        .catch(() => {})
        .finally(() => {
          loading.value.save = false
        })
      if (daRes) {
        dialogVisible.value = false
      }
      break
    default:
      console.log('未知类型')
  }
}

//初始化
getList()
</script>

<template>
  <ContentWrap>
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">{{ t('exampleDemo.add') }}</ElButton>
    </div>

    <div class="custom-tree-container">
      <el-tree
        :data="roleData"
        :props="defaultProps"
        node-key="role_id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node }">
          <span class="custom-tree-node">
            <span>{{ node.data.role_name }}</span>
            <span>
              <a @click="action('edit', node.data)">
                <Icon
                  icon="el:edit"
                  title="编辑"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <a @click="action('addChildren', node.data)">
                <Icon
                  icon="carbon:add-filled"
                  title="创建下级"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <a @click="action('app', node.data)">
                <Icon
                  icon="cib:app-store"
                  title="应用权限"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <a @click="action('menu', node.data)">
                <Icon
                  icon="ep:menu"
                  title="菜单权限"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <a @click="action('function', node.data)">
                <Icon
                  icon="ep:operation"
                  title="功能权限"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <a @click="action('data', node.data)">
                <Icon
                  icon="ep:coin"
                  title="数据权限"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <a @click="action('delete', node.data)">
                <Icon
                  icon="fluent:delete-20-filled"
                  title="删除"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
            </span>
          </span>
        </template>
      </el-tree>
    </div>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add' || actionType == 'addChildren'"
      ref="editRef"
      :formData="formData"
      :roleData="roleData"
    />

    <AppSet v-if="actionType == 'app'" :formData="formData" ref="AppSetRef" />
    <MenuSet v-if="actionType == 'menu'" :formData="formData" ref="MenuSetRef" />
    <FunctionSet v-if="actionType == 'function'" :formData="formData" ref="FaSetRef" />
    <DataSet v-if="actionType == 'data'" :formData="formData" ref="DataSetRef" />

    <template #footer>
      <ElButton type="primary" :loading="loading.save" @click="save(actionType)">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  a {
    padding: 0 3px;

    i {
      margin-top: 5px;
    }
  }
}
</style>
